package com.freesun.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.freesun.shop.entity.Area;
import com.freesun.shop.entity.User;
import com.freesun.shop.entity.UserAddr;
import com.freesun.shop.service.AreaService;
import com.freesun.shop.service.UserAddrService;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
public class UserAddrController {
    @Autowired
    private UserAddrService userAddrService ;

    @Reference(check = false)
    private AreaService areaService;

    @ApiOperation("获取收货地址")
    @GetMapping("/p/address/list")
    public ResponseEntity<List<UserAddr>> findUserAddrs(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<UserAddr> userAddrs = userAddrService.findList(user.getUserId());
        return ResponseEntity.ok(userAddrs);

    }

    @ApiOperation("添加收货地址")
    @GetMapping("/p/area/listByPid")
    public ResponseEntity<List<Area>> listAreaByPid(Long pid){
        List<Area> areas = areaService.listAreaByPid(pid);
        return ResponseEntity.ok(areas);
    }
    @PostMapping("/p/address/addAddr")
    public ResponseEntity<Void>  addUserAddr(@RequestBody UserAddr userAddr){
        userAddr.setCreateTime(LocalDateTime.now());
        userAddr.setUpdateTime(LocalDateTime.now());
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        userAddr.setUserId(user.getUserId());
        userAddr.setStatus(1);
        userAddr.setCommonAddr(0);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }


    @PutMapping("/p/address/defaultAddr/{id}")
    public ResponseEntity<Void> defaultAddr(@PathVariable Long id) {
        userAddrService.updateDefault(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/p/address/addrInfo/{id}")
    public ResponseEntity<UserAddr>  userAddrInfo(@PathVariable("id") Long id){
        UserAddr userAddr = userAddrService.getById(id);
        return ResponseEntity.ok(userAddr);
    }

    @PutMapping("/p/address/updateAddr")
    public ResponseEntity<Void> updateUserAddr(@RequestBody UserAddr userAddr) {
        userAddrService.updateById(userAddr);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/p/address/deleteAddr/{id}")
    public ResponseEntity<Void> deleteUserAddr(@PathVariable("id") Long id){
        userAddrService.removeById(id);
        return ResponseEntity.ok().build();
    }

}
